<template>
  <el-dialog
    title="设置权限"
    :visible.sync="permissionsDialogVisible"
    width="30%"
    @close="handleClose"
  >
    <el-form :model="form" label-width="80px">
      <el-form-item label="用户权限">
        <el-checkbox-group v-model="form.permissions">
          <el-checkbox
            v-for="permission in availablePermissions"
            :key="permission.value"
            :label="permission.value"
          >
            {{ permission.label }}
          </el-checkbox>
        </el-checkbox-group>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script>
import { ref, defineProps, defineEmits } from 'vue'
import { ElMessage } from 'element-plus'
import { updateUserPermissions } from '@/api/user/users'

export default {
  name: 'PermissionsDialog',
  props: {
    permissionsDialogVisible: {
      type: Boolean,
      required: true
    },
    curId: {
      type: [Number, String],
      required: true
    }
  },
  emits: ['close'],
  setup(props, { emit }) {
    const form = ref({
      permissions: []
    })

    const availablePermissions = [
      { label: '用户管理', value: 'user' },
      { label: '角色管理', value: 'role' },
      { label: '权限管理', value: 'permission' },
      { label: '系统管理', value: 'system' }
    ]

    const handleClose = () => {
      emit('close')
      form.value.permissions = []
    }

    const handleSubmit = async () => {
      try {
        await updateUserPermissions(props.curId, form.value.permissions)
        ElMessage.success('权限设置成功')
        handleClose()
      } catch (error) {
        ElMessage.error('权限设置失败：' + error.message)
      }
    }

    return {
      form,
      availablePermissions,
      handleClose,
      handleSubmit
    }
  }
}
</script>

<style scoped>
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>